package repl

import (
	"bufio"
	"fmt"
	"io"

	"gitee.com/yanxingshuyuan/ming/eval"
	"gitee.com/yanxingshuyuan/ming/lexer"
	"gitee.com/yanxingshuyuan/ming/object"
	"gitee.com/yanxingshuyuan/ming/parser"
)

func StartREPL(in io.Reader, out io.Writer) {
	source := bufio.NewScanner(in)
	env := object.NewEnv()

	for {
		fmt.Printf(">> ")
		scanned := source.Scan()
		if !scanned {
			return
		}
		line := source.Text()

		s := lexer.NewLexer(line)

		p := parser.NewParser(s)

		prog := p.ParseProgram()

		fmt.Printf("%#q\n", prog.String())

		result := eval.Eval(prog, env)

		if result != nil {
			io.WriteString(out, result.Inspect())
			io.WriteString(out, "\n")
		} else {
			io.WriteString(out, "nil\n")
		}

		// for _, stmt := range prog.Stmts {
		// fmt.Printf("%s\n", stmt)
		// }

		// n := 0
		// t := s.NextToken()
		// for {
		// 	fmt.Printf("%s\n", t)
		// 	if t.Type == token.EOF || n >= 100 {
		// 		break
		// 	}
		// 	n += 1
		// 	t = s.NextToken()
		// }

	}
}
